package com.cyl.h5.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.manager.ums.domain.entity.Address;
import com.cyl.manager.ums.domain.entity.Feedback;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.domain.query.FeedbackQuery;
import com.cyl.manager.ums.mapper.AddressMapper;
import com.cyl.manager.ums.domain.MemberH5Log;
import com.cyl.manager.ums.domain.dto.AddressDTO;
import com.cyl.manager.ums.service.FeedbackService;
import com.cyl.manager.ums.service.MemberH5LogService;
import com.cyl.manager.ums.service.MemberService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.OssUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.livesass.api.domain.LbsZbrqsj;
import com.ruoyi.livesass.api.mapper.LbsZbrqsjMapper;
import com.ruoyi.livesass.api.service.LbsZbrqsjService;
import com.ruoyi.system.service.ISysConfigService;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.Color;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping
public class H5CommonController {

	@Autowired
	private OssUtils ossUtils;
	@Autowired
	private AddressMapper addressMapper;
	@Autowired
	private RedisService redisService;
	@Autowired
	private FeedbackService feedbackService;
	@Autowired
	private ISysConfigService sysConfigService;
	
    @Autowired
    private MemberH5LogService memberH5LogService;
    
	
    @Autowired
    private MemberService memberService;
    
    
    @Autowired
    private LbsZbrqsjService lbsZbrqsjService;
    
    @Autowired
    private LbsZbrqsjMapper lbsZbrqsjMapper;
    

	@ApiOperation("新增店长申请")
	@Log(title = "店长申请", businessType = BusinessType.INSERT)
	@PostMapping("/h5/feedback/create")
	public ResponseEntity<Integer> add(@RequestBody Feedback feedback) {
		Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
		feedback.setMemberId(member.getId());
		feedback.setNickname(member.getNickname());
		return ResponseEntity.ok(feedbackService.insert(feedback));
	}
	
	
	@ApiOperation("新增意见反馈评价")
	@Log(title = "意见反馈评价", businessType = BusinessType.INSERT)
	@PostMapping("/h5/feedback/createPj")
	public ResponseEntity<Integer> addPj(@RequestBody Feedback feedback) {
		Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
		if(member.getDeptDpId()==null) {
			return ResponseEntity.ok(0);
		}
		feedback.setMemberId(member.getId());
		feedback.setNickname(member.getNickname());
		feedback.setDeptDpId(member.getDeptDpId());
		feedback.setDeptTzId(member.getDeptTzId());
		feedback.setDeptZbjId(member.getDeptZbjId());
		feedback.setSpreaduid(member.getSpreaduid());
		return ResponseEntity.ok(feedbackService.insertPj(feedback));
	}
	
	@ApiOperation("修改反馈评价")
	@Log(title = "修改反馈评价", businessType = BusinessType.UPDATE)
	@PostMapping("/h5/feedback/updatePj")
	public ResponseEntity<Integer> updatePj(@RequestBody Feedback feedback) {
		Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
		if(member.getDeptDpId()==null) {
			return ResponseEntity.ok(0);
		}
		return ResponseEntity.ok(feedbackService.updatePj(feedback));
	}
	
	@ApiOperation("查询意见反馈列表")
    @PostMapping("/h5/feedback/list")
    public ResponseEntity<Page<Feedback>> list(@RequestBody FeedbackQuery query, Pageable page) {
       Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
		if(member.getDeptDpId()==null) {
			return ResponseEntity.ok(null);
		}
	    query.setType("2");
	    query.setMemberId(member.getId());  
        List<Feedback> list = feedbackService.selectList(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }
	
	
	@ApiOperation("查询店铺工作人员信息")
    @PostMapping("/h5/member/selectListGzry")
    public ResponseEntity<Page<Member>> list(Pageable page) {
       Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
		if(member.getDeptDpId()==null) {
			return ResponseEntity.ok(null);
		}
        List<Member> list = memberService.selectListDpry(member.getDeptDpId(), page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }
	
	

	@GetMapping("/h5/area")
	public AjaxResult getAddressList() {
		String addresses = redisService.getAddressList();
		if (StringUtils.isNotEmpty(addresses)) {
			List<AddressDTO> addressDTOList = JSON.parseArray(addresses, AddressDTO.class);
			if (addressDTOList.size() > 0) {
				return AjaxResult.success(addressDTOList);
			}
		}
		QueryWrapper<Address> addressQueryWrapper = new QueryWrapper<>();
		addressQueryWrapper.in("level", Arrays.asList(0, 1, 2));
		List<Address> addressList = addressMapper.selectList(addressQueryWrapper);
		Map<Long, List<Address>> cityMap = addressList.stream().filter(it -> it.getLevel() == 1)
				.collect(Collectors.groupingBy(it -> it.getParentCode()));
		Map<Long, List<Address>> districtMap = addressList.stream().filter(it -> it.getLevel() == 2)
				.collect(Collectors.groupingBy(it -> it.getParentCode()));
		List<AddressDTO> result = new ArrayList<>();
		addressList.stream().filter(it -> it.getLevel() == 0).forEach(it -> {
			AddressDTO dto = new AddressDTO();
			dto.setId(it.getCode());
			dto.setLevel("province");
			dto.setName(it.getName());
			dto.setPid(0L);
			// 获取城市列表
			List<AddressDTO> child = new ArrayList<>();
			if (cityMap.containsKey(it.getCode())) {
				cityMap.get(it.getCode()).forEach(city -> {
					AddressDTO cityDto = new AddressDTO();
					cityDto.setId(city.getCode());
					cityDto.setLevel("city");
					cityDto.setName(city.getName());
					cityDto.setPid(city.getParentCode());
					cityDto.setChildren(districtMap.containsKey(city.getCode())
							? districtMap.get(city.getCode()).stream().map(district -> {
								AddressDTO districtDto = new AddressDTO();
								districtDto.setId(district.getCode());
								districtDto.setLevel("district");
								districtDto.setName(district.getName());
								districtDto.setPid(district.getParentCode());
								return districtDto;
							}).collect(Collectors.toList())
							: Collections.EMPTY_LIST);
					child.add(cityDto);
				});
			}
			dto.setChildren(child);
			result.add(dto);
		});
		redisService.setAddressList(JSON.toJSONString(result));
		return AjaxResult.success(result);
	}

	@ApiOperation("生成二维码图")
	@Log(title = "生成二维码图", businessType = BusinessType.OTHER)
	@PostMapping("/h5/qrcode/create")
	public ResponseEntity<String> qrcodeCreate(String qrValue) {

		if (StrUtil.isBlankIfStr(qrValue)) {
			return ResponseEntity.ok("qrValue | 参数为空");
		}
		
		QrConfig config = new QrConfig(600, 600);
		// 设置边距，即二维码和背景之间的边距
		config.setMargin(3);
		// 设置前景色，即二维码颜色（青色）
		config.setForeColor(Color.CYAN);
		// 设置背景色（灰色）
		config.setForeColor(Color.GRAY);

		// 生成二维码
		String qrBase64 = QrCodeUtil.generateAsBase64(qrValue, config, ImgUtil.IMAGE_TYPE_JPEG);

		return ResponseEntity.ok(qrBase64);
	}

	@PostMapping("/h5/file/upload")
	public AjaxResult uploadFile(MultipartFile file) {
		String url = ossUtils.uploadOneFile(file);
		return AjaxResult.successData(url);
	}

	@GetMapping("/no-auth/config/get")
	public AjaxResult getSysConfig(String configKey) {
		String s = sysConfigService.selectConfigByKey(configKey);
		return AjaxResult.successData(s);
	}

	@GetMapping("/no-auth/debug/get")
	public AjaxResult getDebugConfig(String memberid) {
		String resultConfig = sysConfigService.selectConfigByKey("debugUser");
		if (StrUtil.isBlankIfStr(resultConfig)) {
			return AjaxResult.successData(false);
		}

		if (resultConfig.indexOf("|" + memberid + "|") >= 0) {
			return AjaxResult.successData(true);
		}
		return AjaxResult.successData(false);
	}
	

	
	/*
    @ApiOperation("新增H5会员日志采集")
    @Log(title = "H5会员日志采集", businessType = BusinessType.INSERT)
    @PostMapping("/no-auth/log/put")
	public AjaxResult putDebugLog(@RequestBody MemberH5Log memberH5Log) {
    	
    	 memberH5LogService.insert(memberH5Log);
    	 
    	 return AjaxResult.success();
	}*/

}
